<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实例属性的新写法</title>
</head>
<body>
    <h1>实例属性的新写法</h1>

    <script>
        // 传统写法
        class OldCounter {
            constructor() {
                this.count = 0;
            }
        }

        // 新写法：实例属性可以直接写在类的顶层
        class Counter {
            count = 0;

            increment() {
                this.count++;
            }

            decrement() {
                this.count--;
            }
        }

        const counter = new Counter();
        counter.increment();
        console.log(counter.count); // 1

        // 实例属性的其他写法
        class IncludeFunction {
            myMethod = () => {
                // 这种写法使方法中的this总是指向当前实例
                console.log('实例方法');
            };

            // 属性可以采用表达式的写法
            [Symbol.iterator] = function*() {
                yield 1;
                yield 2;
            }
        }

        // 使用示例
        class Example {
            // 公有字段
            publicField = 'public';
            
            // 私有字段
            #privateField = 'private';
            
            // 静态公有字段
            static staticPublicField = 'static public';
            
            // 静态私有字段
            static #staticPrivateField = 'static private';

            getPrivateField() {
                return this.#privateField;
            }

            static getStaticPrivateField() {
                return Example.#staticPrivateField;
            }
        }

        const example = new Example();
        console.log(example.publicField); // 'public'
        console.log(example.getPrivateField()); // 'private'
        console.log(Example.staticPublicField); // 'static public'
        console.log(Example.getStaticPrivateField()); // 'static private'
    </script>
</body>
</html> 